﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using eTMS.Controllers.NamHocService;
using eTMS.Controllers;
using eTMS.Commons;
namespace eTMS.Forms.ManageList{
    public partial class FrmNamHoc : eTMS.Controls.BaseForm
    {
        public FrmNamHoc()
        {
            InitializeComponent();
        }
        #region Variables
        private NamHocController controller = new NamHocController();
        #endregion
        #region Screen Functions
        //Load All lable text
        private void LoadLanguage(){
			this.Text=NamHocStringMapping.NamHoc;
			this.labelFormTitle.Text=Constants.APP_ADMINISTRATION+" "+NamHocStringMapping.NamHoc;
			this.groupBoxDetail.Text=Constants.APP_DETAIL;
			this.groupBoxList.Text=Constants.APP_LIST;
			this.ColumnSTT.HeaderText=Constants.APP_INDEX;
			labelMaNamHoc.Text=NamHocStringMapping.MaNamHoc;
			ColumnMaNamHoc.HeaderText=NamHocStringMapping.MaNamHoc;
            ColumnMaNamHoc.DefaultCellStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
			labelTenNamHoc.Text=NamHocStringMapping.TenNamHoc;
			ColumnTenNamHoc.HeaderText=NamHocStringMapping.TenNamHoc;
			labelNgayBatDau.Text=NamHocStringMapping.NgayBatDau;
			ColumnNgayBatDau.HeaderText=NamHocStringMapping.NgayBatDau;
            ColumnNgayBatDau.DefaultCellStyle.Format=Constants.APP_DATE_FORMAT;
			labelNgayKetThuc.Text=NamHocStringMapping.NgayKetThuc;
			ColumnNgayKetThuc.HeaderText=NamHocStringMapping.NgayKetThuc;
            ColumnNgayKetThuc.DefaultCellStyle.Format=Constants.APP_DATE_FORMAT;
			labelNamHocHienTai.Text=NamHocStringMapping.NamHocHienTai;
			ColumnNamHocHienTai.HeaderText=NamHocStringMapping.NamHocHienTai;
		    //Search
		    this.groupBoxFilter.Text=Constants.APP_SEARCH;
			labelMaNamHocFilter.Text=NamHocStringMapping.MaNamHoc;	
			cbkMaNamHocFilter.Text=Constants.APP_SEARCH;		
			cbkTenNamHocFilterExact.Text=Constants.APP_SEARCH_EXACT;
			labelTenNamHocFilter.Text=NamHocStringMapping.TenNamHoc;
			labelNgayBatDauFilterFROM.Text=NamHocStringMapping.NgayBatDau;
			labelNgayBatDauFilterTO.Text=NamHocStringMapping.NgayBatDau;
			cbkNgayBatDauFilterFROM.Text=Constants.APP_SEARCH;
			cbkNgayBatDauFilterTO.Text=Constants.APP_SEARCH;
			labelNgayKetThucFilterFROM.Text=NamHocStringMapping.NgayKetThuc;
			labelNgayKetThucFilterTO.Text=NamHocStringMapping.NgayKetThuc;
			cbkNgayKetThucFilterFROM.Text=Constants.APP_SEARCH;
			cbkNgayKetThucFilterTO.Text=Constants.APP_SEARCH;
			txtNamHocHienTaiFilter.Items.Add(Constants.APP_ALL);			
			txtNamHocHienTaiFilter.Items.Add(Constants.APP_TRUE);		
			txtNamHocHienTaiFilter.Items.Add(Constants.APP_FALSE);		
			labelNamHocHienTaiFilter.Text=NamHocStringMapping.NamHocHienTai;
		    //end
        }
        //Get entity selected from datagrid
        private NamHocEntity GetObject(){
		    NamHocEntity o=controller.MapDataRowToObject(((DataRowView)gridData.SelectedRows[0].DataBoundItem).Row);
		    return o;
        }        
        //Get entites selected from datagrid
        private List<DataRow> GetSelectedDataRows(){
		    List<DataRow> ls=new List<DataRow>();
            for(int i=0;i<gridData.SelectedRows.Count;i++){
                ls.Add(GetDataRow(gridData.SelectedRows[i].Index));
            }
		    return ls;
        }
        //Get the selected data row in datagrid
        private DataRow GetSelectedDataRow(){
			DataRow row=GetDataRow(gridData.SelectedRows[0].Index);
		    return row;
        }
         //Get the selected data row in datagrid
        private DataRow GetDataRow(int index){
			DataRow row=((DataRowView)gridData.Rows[index].DataBoundItem).Row;
		    return row;
        }
        //Reset all textbox
        private void ClearScreen(){
			txtMaNamHoc.Text="";
			txtTenNamHoc.Text="";
			errorProviderData.Clear();
        }
        //Lock-Unlock control in screen
        private void LockScreen(bool IsLocked){            
            ucCommand.LockControl(IsLocked);
			txtMaNamHoc.ReadOnly = IsLocked;
			txtTenNamHoc.ReadOnly = IsLocked;
			txtNgayBatDau.ReadOnly = IsLocked;
			txtNgayKetThuc.ReadOnly = IsLocked;
			txtNamHocHienTai.Enabled = !IsLocked;
        }
        //Copy data from control in screen to object
        private void CopyFromSreen(NamHocEntity o){
			 o.MaNamHoc=(int)txtMaNamHoc.Value;
			 o.TenNamHoc=Convert.ToString(txtTenNamHoc.Text);
			 o.NgayBatDau=txtNgayBatDau.Value;
			 o.NgayKetThuc=txtNgayKetThuc.Value;
			 o.NamHocHienTai=txtNamHocHienTai.Checked;
        }
        //Bind data from object to control in screen
        private void CopyToSreen(NamHocEntity o){
		    if(!o.IsNullMaNamHoc){
			txtMaNamHoc.Text=Convert.ToString(o.MaNamHoc);
		    }
		    if(!o.IsNullTenNamHoc){
			txtTenNamHoc.Text=Convert.ToString(o.TenNamHoc);
		    }
		    if(!o.IsNullNgayBatDau){
			txtNgayBatDau.Value=o.NgayBatDau;
		    }
		    if(!o.IsNullNgayKetThuc){
			txtNgayKetThuc.Value=o.NgayKetThuc;
		    }
		    if(!o.IsNullNamHocHienTai){
			txtNamHocHienTai.Checked=o.NamHocHienTai;
		    }
        }
        //Validate all data from control in screen before Save data
        protected bool ValidateScreen(){
		    bool result=true;
		    if(!result){
				ShowInfo(Constants.MSS_REQUIRE_FIELD);
		    }
		    if(result){
				//Check if exists MaNamHoc				
				bool existsMaNamHoc=controller.CheckExistsMaNamHoc(txtMaNamHoc.Value);
				bool editexists=false;
				if(Flag==ACTIONENUM.Edit){
					DataRow row = GetSelectedDataRow();
					int newVal=(int)txtMaNamHoc.Value;
					editexists=Convert.ToString(row["MaNamHoc"])!=Convert.ToString(newVal);
				}
				if(existsMaNamHoc&&((Flag==ACTIONENUM.AddNew)||editexists)){
					result = false; 					
					errorProviderData.SetError(txtMaNamHoc,Constants.MSS_ERROR_DATA_UNIQUE);
					txtMaNamHoc.Focus();
					ShowInfo(Constants.MSS_ERROR_EXISTS_DATA);
				}
				else
				{
					errorProviderData.SetError (txtMaNamHoc, "");
				}
			}
		    return result;
        }
        //Copy data from selected object to control in screen
        private void BindInfo(){
			if (gridData.SelectedRows.Count == 0) return;
			if(gridData.SelectedRows[0].Index<gridData.Rows.Count){
				NamHocEntity o=GetObject();	
				CopyToSreen(o);
		    }
        }    
        #endregion
        #region Business
        //AddNew data to database
        private bool AddNewData()
        {
			bool rval=false;
            controller.ResetObject();		
		    CopyFromSreen(controller.NamHocObject);		    
            rval=controller.AddNew();
            if(rval){
				DataRow row=controller.Table.NewRow();
				row["STT"]=controller.Table.Rows.Count+1;
				controller.MapObjectToDataRow(row);
				controller.Table.Rows.Add(row);
				gridData.DataSource=null;
				gridData.DataSource=controller.Table;
            }
            return rval;
        }
        //Update data to database
        private bool UpdateData()
        {      
			DataRow row=GetSelectedDataRow();
            controller.LoadObject((Int32)row["NamHoc_ID"]);		
		    CopyFromSreen(controller.NamHocObject);
		    bool rval=controller.Update();
            if(rval){
				controller.MapObjectToDataRow(row);
				gridData.InvalidateRow(gridData.SelectedRows[0].Index);
            }
            return rval;
        }
        //Delete data from database
        private bool DeleteData()
        {
            List<DataRow> ls=GetSelectedDataRows();
            if(ls.Count==0)return false;  
            bool rval=true; 
            try{
                gridData.DataSource = null;
				foreach(DataRow row in ls){
					if(controller.DeleteByID((Int32)row["NamHoc_ID"])){
						 this.controller.Table.Rows.Remove(row);
					}	
					else
					{
						rval=false;
					}				
				}
				this.controller.ResetTableIndex();
                gridData.DataSource = this.controller.Table;
            }
            catch{
				return false;
            }
            return true;
        }        
        #endregion
        #region DataBinding 
        //Bind data to datagrid
        private void LoadData(){
            gridData.AutoGenerateColumns = false;
            gridData.DataSource=controller.Table;     
            gridData.AutoResizeColumns();       
        }
        #endregion
        #region Windows Control EventHandlers
        private void FrmNamHoc_Load(object sender, EventArgs e)
        {
			LoadLanguage();
            LoadData();
            LockScreen(true);
            this.groupBoxFilter.ToggleCollapsed();
        }       
		private void gridData_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
			BindInfo();
        }   
        private void ucCommand_OnAddNew(object sender, EventArgs e)
        {
			ClearScreen();
            LockScreen(false);
            Flag=ACTIONENUM.AddNew;
			txtTenNamHoc.Focus();
        }
        private void ucCommand_OnDelete(object sender, EventArgs e)
        {
			if(gridData.SelectedRows.Count==0){
                ShowInfo(Constants.MSS_CHOOSERECORD_REQUIRE);
                return;
            }
            if(!Confirm(Constants.MSS_CONFIRM_DELETE))return;
            DeleteData();
			this.gridData.Focus();
        }
        private void ucCommand_OnEdit(object sender, EventArgs e)
        {
			if(gridData.SelectedRows.Count==0){
                ShowInfo(Constants.MSS_CHOOSERECORD_REQUIRE);
                return;
            }
            LockScreen(false);
            Flag=ACTIONENUM.Edit;
			txtTenNamHoc.Focus();
        }
        private void ucCommand_OnSave(object sender, EventArgs e)
        {
			if(!ValidateScreen())
				return;
            if(Flag==ACTIONENUM.Edit){
                if(UpdateData()){
                    ShowInfo(Constants.MSS_SAVE_SUCCESS);
                }
                else{
                    ShowWarning(Constants.MSS_SAVE_FAILE);
                }
                gridData.Focus();
            }
            else{
                if(AddNewData()){
                    ShowInfo(Constants.MSS_SAVE_SUCCESS);
                }
                else{
                    ShowWarning(Constants.MSS_SAVE_FAILE);
                }
            }
            LockScreen(true);
            Flag=ACTIONENUM.None;
        }
        private void ucCommand_OnSkip(object sender, EventArgs e)
        {
			LockScreen(true);  
			if(Flag==ACTIONENUM.AddNew){			
				ClearScreen();    
				ucCommand.SetFocusAddNew();
			}
			else if(Flag==ACTIONENUM.Edit){				
				BindInfo();
				this.gridData.Focus();
			}      
            Flag=ACTIONENUM.None;
        }
        #endregion   
        #region Filters
        private string GetFilter(){
			string strFilter="";
			if(cbkMaNamHocFilter.Checked){
				strFilter+=" AND MaNamHoc="+txtMaNamHocFilter.Value.ToString();
			}			
			if(txtTenNamHocFilter.Text.Trim()!=""){
				if(cbkTenNamHocFilterExact.Checked){
					strFilter+=" AND TenNamHoc='"+txtTenNamHocFilter.Text.Trim()+"'";
				}
				else{
					strFilter+=" AND TenNamHoc LIKE '%"+txtTenNamHocFilter.Text.Trim()+"%'";
				}
			}	
			if(cbkNgayBatDauFilterFROM.Checked){
				strFilter+=" AND NgayBatDau >= #"+txtNgayBatDauFilterFROM.Value.ToString()+"#";
			}	
			if(cbkNgayBatDauFilterTO.Checked){
				strFilter+=" AND NgayBatDau <= #"+txtNgayBatDauFilterTO.Value.ToString()+"#";
			}		
			if(cbkNgayKetThucFilterFROM.Checked){
				strFilter+=" AND NgayKetThuc >= #"+txtNgayKetThucFilterFROM.Value.ToString()+"#";
			}	
			if(cbkNgayKetThucFilterTO.Checked){
				strFilter+=" AND NgayKetThuc <= #"+txtNgayKetThucFilterTO.Value.ToString()+"#";
			}		
			if(txtNamHocHienTaiFilter.SelectedIndex>0){
				strFilter+=" AND NamHocHienTai="+(txtNamHocHienTaiFilter.SelectedIndex==1?"1":"0");
			}
			if(strFilter.Length>0)
				strFilter=strFilter.Substring(4);
			return strFilter;
		}
		private void FilterData(){		
            gridData.ClearSelection();
			controller.Table.DefaultView.RowFilter=GetFilter();
		}
        private void btnSearch_Click(object sender, EventArgs e)
        {
			FilterData();
        }
        #endregion   
    }
}
